import Taro from '@tarojs/taro'
import {
    md5
} from './md5'

const ERROR_CODE = {
    success: 1, // 1是请求成功
    error: 0 // 0是请求失败
}

/**
 * 获取当前时间字符串
 * @author luozhou
 * @DateTime 2019-09-28T15:28:19+0800
 * @return   {[type]}                 [description]
 */
const requestTime = () => {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = parseInt(myDate.getMonth() + 1) > 9 ? parseInt(myDate.getMonth() + 1) : "0" + parseInt(myDate.getMonth() + 1);
    var day = parseInt(myDate.getDate()) > 9 ? parseInt(myDate.getDate()) : "0" + parseInt(myDate.getDate());

    var hour = parseInt(myDate.getHours()) > 9 ? parseInt(myDate.getHours()) : "0" + parseInt(myDate.getHours());
    var minute = parseInt(myDate.getMinutes()) > 9 ? parseInt(myDate.getMinutes()) : "0" + parseInt(myDate.getMinutes());
    var second = ((parseInt(myDate.getSeconds()) > 9 ? "" + parseInt(myDate.getSeconds()) : "0" + parseInt(myDate.getSeconds()))) + "0";

    var rand = "";
    for (var i = 0; i < 5; i++) {
        var r = Math.floor(Math.random() * 10);
        rand += r;
    }
    return "" + year + "" + month + "" + day + "" + hour + "" + minute + "" + second + "" + rand;
}
/**
 * 生成设备唯一编码
 * @author luozhou
 * @DateTime 2019-09-28T15:29:02+0800
 * @return   {[type]}                 [description]
 */
const getUUID = () => {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

// 光明 wx351fe20781cceb48
// 湖南 wx2b4470ddc9a99702
// 平江 wx29c6b074b2510fb4
//wxf1306f6e453e0202
// 默认参数设置
export const config = {
    // version: "3.0.0",
    // appId: "wx2b4470ddc9a99702",
    // device: ['weapp', 'touch', 'rn','ink','h5'].indexOf(process.env.TARO_ENV), //device 小程序=0   ipad=2  触摸屏=1,h5=4
    // deviceId: getUUID(),
    // requestTime: requestTime(),
    // sign: md5('wx2b4470ddc9a99702' + requestTime()),
}

const statusFn = (status = 1) => {

}

/**
 * 排出没用对象
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
const dataType = (data) =>{
    let newObj = {}
    for( let key in data){
        if(![undefined,'undefined',null,'null','NaN',NaN].includes(data[key])){
            newObj[key] = data[key]
        }
    }
    return newObj;
}



/**
 * 发请求函数
 * @author luozhou
 * @DateTime 2019-09-28T10:16:41+0800
 * @param    {String}                 url    [请求链接]
 * @param    {Object}                 data   [请求数据]
 * @param    {String}                 method [请求类型]
 * @return   {[type]}                        [promise对象]
 */
const requestFn = async (url = '', data = {}, method = 'POST') => {

    const header = {}
    if (method === 'POST') {
        header['content-type'] = 'application/x-www-form-urlencoded'
    }
    return Taro.getStorage({
        key: 'token'
    }).then(res => {
        return Taro.request({
            url: url,
            data: {
                token: res.data,
                ...dataType(config),
                ...dataType(data)
            },
            method: method,
            header
        })
    }).catch(() => {
        return Taro.request({
            url: url,
            data: {
                ...dataType(config),
                ...dataType(data)
            },
            method: method,
            header
        })
    })

}

/**
 * 发生get请求
 * @author luozhou
 * @DateTime 2019-09-28T09:27:38+0800
 * @param    {String}                 options.url       [请求链接]
 * @param    {Boolean}                options.isLoading [是否显示loading动画]
 * @param    {Boolean}                options.isMark    [是否显示透明蒙层]
 * @param    {Boolean}                options.isMessage [是否弹出错误信息]
 * @param    {Boolean}                options.complete  [是否返回完整数据]
 * @param    {Object}                 options.complete  [请求参数]
 * @param    {Function}               options.success   [成功回掉函数]
 * @param    {Function}               options.error     [失败回掉函数]
 * @param    {String}                 options.method    [请求类型]
 * @return   {[type]}                                   [description]
 */
const request = ({
    url = "",
    isLoading = false,
    isMark = true,
    isMessage = false,
    complete = false,
    data = {},
    success = () => {},
    error = null,
    method = "POST"
}) => {
    //如果值为true的话，显示正在加载动画
    if (isLoading) {
        Taro.showLoading({
            title: '正在加载中...'
        })
    }
    requestFn(url, data, method).then((response) => {
        if (response.data.code == 110 || (isMessage && response.data.status == 0)) {
            Taro.showToast({
                title: response.data.message,
                icon: 'none',
                duration: 3000
            });
        }
        //请求接口成功
        if (response.data.status == ERROR_CODE.success) {
            // 如果值为true的话返回完整数据
            if (complete) {
                success && success(response.data)
                // complete 不为 true的话返回 result 数据
            } else {
                success && success(response.data.result)
            }
            if (isLoading) {
                setTimeout(() => {
                    Taro.hideLoading();
                }, 300)
            }
        } else {
            // 如果有传error回掉函数的话
            if (error) {
                error(response.data)
            } else {
                if (isLoading) {
                    setTimeout(() => {
                        Taro.hideLoading();
                    }, 300)
                }
            }
        }
    })
}



export const Ajax = {
    request
}
